/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.jsf;

import javax.faces.model.DataModel;
import java.io.Serializable;
import java.util.List;

/**
 * JSF utility class implementing the JSF DataModel class providing real paging functionality
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 20:39 08.09.11
 *
 * @author Peter Herber
 * @version 1.0
 */
public class PagedListDataModel<T> extends DataModel<T> implements Serializable {

    private int rowIndex = -1;
    private int totalNumRows;
    private int pageSize;
    private List<T> list;

    public PagedListDataModel() {
        super();
    }

    public PagedListDataModel(List list, int totalNumRows, int pageSize) {
        super();
        setWrappedData(list);
        this.totalNumRows = totalNumRows;
        this.pageSize = pageSize;
    }

    public boolean isRowAvailable() {
        if (list == null) {
            return false;
        }

        int rowIndex = getRowIndex();

        return (rowIndex >= 0 && rowIndex < list.size());
    }

    public int getRowCount() {
        return totalNumRows;
    }

    public T getRowData() {
        if (list == null) {
            return null;
        } else if (!isRowAvailable()) {
            throw new IllegalArgumentException();
        } else {
            int dataIndex = getRowIndex();
            return list.get(dataIndex);
        }
    }

    public int getRowIndex() {
        return (rowIndex % pageSize);
    }

    public void setRowIndex(int rowIndex) {
        this.rowIndex = rowIndex;
    }

    public Object getWrappedData() {
        return list;
    }

    @SuppressWarnings({"unchecked"})
    public void setWrappedData(Object list) {
        this.list = (List<T>) list;
    }

}
